<template>
	<div class="me">
		<div class="container">
      <div class="userinfo">
        <img :src="userInfo.avatarUrl" alt="">
        <p v-if="userInfo.nickName !== '点击登录'">{{ userInfo.nickName }}</p>
        <button v-else open-type="getUserInfo" lang="zh_CN" @getuserinfo="doLogin">{{ userInfo.nickName }}</button>
      </div>
      <year-progress></year-progress>
      <button v-if="userInfo.openId" @click='scanBook' class='btn'>添加图书</button>
    </div>
  </div>
</template>
<script>
import qcloud from 'wafer2-client-sdk'
import config from '@/utils/config'
import { showSuccess, showModal } from '@/utils/utils'
import { post } from '@/utils/api'
import yearProgress from '@/pages/components/yearProgress'

export default {
  data () {
    return {
      userInfo: {}
    }
  },
  created () {
    this.userInfo = wx.getStorageSync('userInfo') || {
      avatarUrl: require('../../../static/images/unlogin.png'),
      nickName: '点击登录'
    }
  },
  components: {
    yearProgress
  },
  onshow () {
    console.log('yearProgress onshow')
  },
  methods: {
    async addbook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userInfo.openId
      })
      console.log(res)
      showModal('添加成功', `${res.data.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            this.addbook(res.result)
          }
        }
      })
    },
    doLogin: function () {
      qcloud.setLoginUrl(config.login)
      const session = qcloud.Session.get()

      if (session) {
        // 第二次登录
        // 或者本地已经有登录态
        // 可使用本函数更新登录态
        qcloud.loginWithCode({
          success: res => {
            // this.setData({ userInfo: res, logged: true })
            // util.showSuccess('登录成功')
            console.log('second-------', res)
          },
          fail: err => {
            console.error('second----', err)
            // util.showModel('登录错误', err.message)
          }
        })
      } else {
        // 首次登录
        qcloud.login({
          success: userInfo => {
            showSuccess('登录成功')
            wx.setStorageSync('userInfo', userInfo)
            this.userInfo = userInfo
          },
          fail: err => {
            console.log('first:', err)
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .me{
    .container{
      padding:0 30rpx;
      .userinfo{
        margin-top:100rpx;
        text-align:center;
        img{
          width: 150rpx;
          height:150rpx;
          margin: 20rpx;
          border-radius: 50%;
        }
      }
    }
  }
</style>